//
//  BIZMovieSitcomView.m
//  biz
//
//  Created by zhangfuwei on 2017/3/23.
//  Copyright © 2017年 jieshuibao. All rights reserved.
//

#import "BIZMovieSitcomView.h"
#import "BIZSitcomListTableViewCell.h"
#import "BIZSitcomIntroduceTableViewCell.h"
#import "BIZSitcomTeacherInfoCell.h"
#import "BIZMoviePlaySitcomListDataModel.h"
#import "BIZNoConsultorCell.h"

static CGFloat  kVideoWatchNumLabH = 29;
static CGFloat  kSliderButtonH = 37;
static CGFloat  kSliderUnderLineH = 1.5;
static CGFloat  kSliderButtonEdgeMargin = 0;
static CGFloat  kTitleBgViewH = 38;
static CGFloat  kTableViewTopMargin = 20;


static NSString *kSitcomListTabCellResueID = @"kSitcomListTabCellResueID";
static NSString *kSitcomTeacherInfoCellResueID = @"kSitcomTeacherInfoCellResueID";
static NSString *kSitcomIntroduceCellResueID = @"kSitcomIntroduceCellResueID";
static NSString *kNodataCellResueID = @"kNodataCellResueID";
static NSString *kDefaultPlayingVideoID = @"-123456789";

typedef enum : NSUInteger {
    BIZMovieSitcomViewDisplayChapter = 0,
    BIZMovieSitcomViewDisplayDetail,
    BIZMovieSitcomViewDisplayTeacherInfo
} BIZMovieSitcomViewDisPlayState;

@interface BIZMovieSitcomView ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation BIZMovieSitcomView{
    UIButton     *_videoWatchNumBtn; // 观看次数
    UIView      *_titleBgView; //  标题背景与
    UILabel     *_titleLabel;   // 标题
    
    UITableView *_tableView;    // 内容视图
    
    UIButton    *_chapterButton; // 标签按钮
    UIButton    *_detailButton;
    UIButton    *_teacherInfoButton;
    
    UIView      *_chapterUnderLine; // 标签下划线
    UIView      *_detailUnderLine;
    UIView      *_teacherInfoUnderLine;
    
    NSString    *_isPlayingVideoID;
    BIZMovieSitcomViewDisPlayState _displayState;
    int         _lastId;/* 数据源最后的id*/
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(instancetype)init {
    self = [super init];
    if (self) {
        [self setConfig];
        [self loadUI];
        self.backgroundColor = [UIColor blackColor];
    };
    return self;
}

- (void)setConfig {
    _isPlayingVideoID = kDefaultPlayingVideoID;
    _lastId = 1;
}

- (void)loadUI {
    //  观看次数
    _videoWatchNumBtn = [[UIButton alloc] init];
    _videoWatchNumBtn.backgroundColor = [UIColor blackColor];
    _videoWatchNumBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _videoWatchNumBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    // 标题背景
    _titleBgView = [[UIView alloc] init];
    _titleBgView.backgroundColor = COLOR_UNLINE_GREY;
    
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.font = [UIFont boldSystemFontOfSize:15];
    _titleLabel.backgroundColor = [UIColor whiteColor];
    _titleLabel.textColor = COLOR_WORD_BLACK;
    _titleLabel.text = @"播放视频标题";
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    
    // 内容视图
    _tableView  = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
//    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreSitcomList)];

    [_tableView registerClass:[BIZSitcomListTableViewCell class] forCellReuseIdentifier:kSitcomListTabCellResueID];
    [_tableView registerClass:[BIZSitcomIntroduceTableViewCell class] forCellReuseIdentifier:kSitcomIntroduceCellResueID];
    [_tableView registerClass:[BIZSitcomTeacherInfoCell class] forCellReuseIdentifier:kSitcomTeacherInfoCellResueID];
    [_tableView registerNib:[UINib nibWithNibName:@"BIZNoConsultorCell" bundle:nil] forCellReuseIdentifier:kNodataCellResueID];

    _tableView.delegate     = self;
    _tableView.dataSource   = self;
    _tableView.estimatedRowHeight   = 50;
    _tableView.rowHeight            = UITableViewAutomaticDimension;
    _tableView.tableFooterView      = [UIView new];
    UIView  *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, kTableViewTopMargin)];
    header.backgroundColor = [UIColor whiteColor];
    _tableView.tableHeaderView = header;
    _tableView.separatorStyle       = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    //  标签按钮
    _chapterButton      = [UIButton buttonWithType:UIButtonTypeCustom];
    _teacherInfoButton  = [UIButton buttonWithType:UIButtonTypeCustom];
    _detailButton       = [UIButton buttonWithType:UIButtonTypeCustom];;
    _chapterButton.tag  = 1;
    _detailButton.tag   = 2;
    _teacherInfoButton.tag  = 3;
    
    [_chapterButton addTarget:self action:@selector(clickSliderButtons:) forControlEvents:UIControlEventTouchUpInside];
    [_detailButton addTarget:self action:@selector(clickSliderButtons:) forControlEvents:UIControlEventTouchUpInside];
    [_teacherInfoButton addTarget:self action:@selector(clickSliderButtons:) forControlEvents:UIControlEventTouchUpInside];

    [_chapterButton setTitle:@"课程章节" forState:UIControlStateNormal];
    [_detailButton  setTitle:@"课程详情" forState:UIControlStateNormal];
    [_teacherInfoButton  setTitle:@"老师简介" forState:UIControlStateNormal];
    
    [_chapterButton setBackgroundColor:[UIColor whiteColor]];
    [_detailButton  setBackgroundColor:[UIColor whiteColor]];
    [_teacherInfoButton  setBackgroundColor:[UIColor whiteColor]];
    
    _chapterUnderLine   = [[UIView alloc] init];
    _detailUnderLine    = [[UIView alloc] init];
    _teacherInfoUnderLine    = [[UIView alloc] init];
    
    // 设置字体,下划线颜色
    [self changeColorForBtnAndUnderLine];
    
    [self addSubview:_titleBgView];
    [_titleBgView addSubview:_titleLabel];
    
    [self addSubview:_videoWatchNumBtn];
    [self addSubview:_tableView];
    
    [self addSubview:_chapterUnderLine];
    [self addSubview:_detailUnderLine];
    [self addSubview:_teacherInfoUnderLine];
    
    [self addSubview:_teacherInfoButton];
    [self addSubview:_chapterButton];
    [self addSubview:_detailButton];

}


- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat btnW = (Main_Screen_Width-kSliderButtonEdgeMargin*2)/3;
    
    _videoWatchNumBtn.frame = CGRectMake(0, 0, Main_Screen_Width, kVideoWatchNumLabH);
    
    // 标题视图
    _titleBgView.frame = CGRectMake(0, kVideoWatchNumLabH, Main_Screen_Width, kTitleBgViewH +5);
    _titleLabel.frame = CGRectMake(0, 0, Main_Screen_Width, kTitleBgViewH);
    
    //  标签按钮
    CGFloat bgnY = kVideoWatchNumLabH + kTitleBgViewH +5;
    
    _chapterButton.frame = CGRectMake(kSliderButtonEdgeMargin, bgnY, btnW, kSliderButtonH);
    _detailButton.frame = CGRectMake(kSliderButtonEdgeMargin+btnW, bgnY, btnW, kSliderButtonH);
    _teacherInfoButton.frame = CGRectMake(kSliderButtonEdgeMargin+btnW*2, bgnY, btnW, kSliderButtonH);

    //  标签下划线
    _chapterUnderLine.frame = CGRectMake(kSliderButtonEdgeMargin, bgnY+kSliderButtonH, btnW, kSliderUnderLineH);
    _detailUnderLine.frame = CGRectMake(kSliderButtonEdgeMargin+btnW, bgnY+kSliderButtonH, btnW, kSliderUnderLineH);
    _teacherInfoUnderLine.frame = CGRectMake(kSliderButtonEdgeMargin+btnW*2,bgnY+ kSliderButtonH, btnW, kSliderUnderLineH);

    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_chapterUnderLine.mas_bottom);
        make.left.right.bottom.equalTo(self);
    }];

}

-(void)setDataM:(BIZMoviePlaySitcomListDataModel *)dataM {
    _dataM = dataM;
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"播放%ld次",dataM.watchNum] attributes:@{NSFontAttributeName:CHINESE_SYSTEM(12),NSForegroundColorAttributeName:HEXCOLOR(0xcb9217)}];
    
    [attStr setAttributes:@{NSForegroundColorAttributeName:HEXCOLOR(0x999999),NSFontAttributeName:CHINESE_SYSTEM(12)} range:NSMakeRange(0, 2)];
    [attStr setAttributes:@{NSForegroundColorAttributeName:HEXCOLOR(0x999999),NSFontAttributeName:CHINESE_SYSTEM(12)} range:NSMakeRange(attStr.length-1, 1)];

    [_videoWatchNumBtn setAttributedTitle:attStr forState:UIControlStateNormal];
//    [self requestMoviePlaySitcomScrListWithSitcomId:dataM.uuid pageIndex:@(_lastId) pageEnd:@(999)];
}

- (void)setScrListModel:(BIZMoviePlaySitcomScrListModel *)scrListModel {
    _scrListModel = scrListModel;
    [_tableView reloadData];
}

#pragma mark -- delegate,datasource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (_displayState == BIZMovieSitcomViewDisplayChapter) {
        return self.scrListModel.data.count?:1;
    }else {
        
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_displayState == BIZMovieSitcomViewDisplayChapter) {
        if (!self.scrListModel.data.count) { // 单集列表为空
            BIZNoConsultorCell *noDataCell = [tableView dequeueReusableCellWithIdentifier:kNodataCellResueID forIndexPath:indexPath];
            noDataCell.errorMsg = @"单集列表更新中";
            noDataCell.backgroundColor = [UIColor whiteColor];
            return noDataCell;
        }
        BIZMoviePlaySitcomScrListDataModel *dataModel = self.scrListModel.data[indexPath.row];
        
        BIZSitcomListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSitcomListTabCellResueID forIndexPath:indexPath];
        
        cell.dataModel = dataModel;
        cell.isPlayingVideoID = _isPlayingVideoID;
//        cell.block = [self returnCellBlock];
        cell.isFirstCell = !indexPath.row;
        cell.isLastCell = indexPath.row == self.scrListModel.data.count-1 ?YES:NO;
        
        return cell;
    }else if (_displayState == BIZMovieSitcomViewDisplayDetail ){
        
        BIZSitcomIntroduceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kSitcomIntroduceCellResueID forIndexPath:indexPath];
        cell.sitcomIntroduce = _dataM.courseIntroduce;
        return cell;
    }else {
        
        BIZSitcomTeacherInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:kSitcomTeacherInfoCellResueID forIndexPath:indexPath];
        cell.dataM = _dataM;
        return cell;
        
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.scrListModel.data.count) {
        return;
    }
    BIZMoviePlaySitcomScrListDataModel *dataModel = self.scrListModel.data[indexPath.row];

    _titleLabel.text = dataModel.title;
    
    !self.newBlock ?:self.newBlock(indexPath);
}

- (void)setTitle:(NSString *)title {
    _title = title;
    _titleLabel.text = title;
}
#pragma mark -- 点播单集列表
//- (void)requestMoviePlaySitcomScrListWithSitcomId:(NSString *)sitcomId pageIndex:(NSNumber *)index pageEnd:(NSNumber *)end {
//    
//    NSDictionary *param2 = @{@"sitcomId":sitcomId?:@"",@"pageIndex":index?:@1,@"pageEnd":end?:@999};
//    [RequestTool POST:kMoviePlaySitcomScrUrl
//           parameters:param2
//             progress:nil
//              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//            
//                  [self stopRefresh];
//
//                  BIZMoviePlaySitcomScrListModel *sitcomScrListM = [BIZMoviePlaySitcomScrListModel yy_modelWithJSON:responseObject];
//                  if (sitcomScrListM.code.intValue == 1) {
//                      
//                      if (index.intValue == 1) {
//                          
//                          _scrListModel = sitcomScrListM;
//
//                      }else{
//                          _scrListModel.data = [_scrListModel.data arrayByAddingObjectsFromArray:sitcomScrListM.data];
//                      }
//                      _lastId += (int)sitcomScrListM.data.count;
//                      [_tableView reloadData];
//                      
//                  }else if (sitcomScrListM.code.intValue == 2){ // 未登录
//                      //  因为不在主线程,所以不能展示toast
//
//                      [MBProgressHUD showWarnMessage:@"请登录"];
//                      
//                  }else {
//                      
//                      [MBProgressHUD showWarnMessage:sitcomScrListM.des];
//                  }
//              }
//              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//                  [self stopRefresh];
//                  [MBProgressHUD showErrorMessage:@"网络不给力"];
//                  DeLog(@"error ---%@",error);
//              }
//     ];
//}


#pragma mark -- private methods

- (BIZSitcomListTableViewCellPlayBlock)returnCellBlock {
    BIZSitcomListTableViewCellPlayBlock block = nil;
    __weak BIZMovieSitcomView *weakSelf = self;
    
    block = ^(NSString *videoId,BOOL isStartPlay,NSString *title){
        
        _titleLabel.text = title;
        weakSelf.block ? weakSelf.block(videoId,isStartPlay,title) : nil;
    };
    
    return block;
}

- (void)clickSliderButtons:(UIButton *)btn {
    switch (btn.tag) {
        case 1:
            
            _displayState = BIZMovieSitcomViewDisplayChapter;
            [self changeColorForBtnAndUnderLine];
            [self reloadDataScorollToTop];
            break;
        case 2:
            
            _displayState = BIZMovieSitcomViewDisplayDetail;
            [self changeColorForBtnAndUnderLine];
            [self reloadDataScorollToTop];
            break;
        case 3:
            
            _displayState = BIZMovieSitcomViewDisplayTeacherInfo;
            [self changeColorForBtnAndUnderLine];
            [self reloadDataScorollToTop];
            break;

        default:
            break;
    }
}

- (void)changeColorForBtnAndUnderLine{
    
    [_chapterButton setTitleColor:_displayState == BIZMovieSitcomViewDisplayChapter? COLOR_WORD_BLUE:COLOR_WORD_BLACK forState:UIControlStateNormal];
    [_detailButton  setTitleColor:_displayState == BIZMovieSitcomViewDisplayDetail? COLOR_WORD_BLUE:COLOR_WORD_BLACK forState:UIControlStateNormal];
    [_teacherInfoButton  setTitleColor:_displayState == BIZMovieSitcomViewDisplayTeacherInfo? COLOR_WORD_BLUE:COLOR_WORD_BLACK forState:UIControlStateNormal];

    _chapterUnderLine.backgroundColor   = _displayState == BIZMovieSitcomViewDisplayChapter?COLOR_UNLINE_BLUE:COLOR_UNLINE_GREY;
    _detailUnderLine.backgroundColor    = _displayState == BIZMovieSitcomViewDisplayDetail?COLOR_UNLINE_BLUE:COLOR_UNLINE_GREY;
    _teacherInfoUnderLine.backgroundColor    = _displayState == BIZMovieSitcomViewDisplayTeacherInfo?COLOR_UNLINE_BLUE:COLOR_UNLINE_GREY;
    
}

- (void)reloadDataScorollToTop {
    
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    [_tableView reloadData];
}

- (void)reloadTableViewDataWithIsPlayingVideoID:(NSString *)videoID {
    _isPlayingVideoID = videoID;
    [_tableView reloadData];
}


//- (void)loadMoreSitcomList {
//    if (_displayState != BIZMovieSitcomViewDisplayChapter) {
//        [self stopRefresh];
//        return;
//    }
////    [self requestMoviePlaySitcomScrListWithSitcomId:_dataM.uuid pageIndex:@(_lastId) pageEnd:@(_lastId+9)];
//}

//- (void)stopRefresh
//{
//    !_tableView.mj_header.isRefreshing ? : _tableView.mj_header.endRefreshing;
//    !_tableView.mj_footer.isRefreshing ? : _tableView.mj_footer.endRefreshing;
//}

@end
